//index.js
import { Topic } from "../../model/Topic";
import { Sign } from "../../model/Sign";
import { Utils } from "../../utils/util.js";
const topic = new Topic();
const sign = new Sign();
const utils = new Utils();
//获取应用实例
const app = getApp()

Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        categoryId: null,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        checkStatus: false,
        checksuccess: false,
        checklist: false,
        navState: false,
        categories: [],
        signDetail: {},
        topicList: [],
        keyword: "",
        upload: false,
        loadtype: "loading",
        subCommentState: false,
        commentPid: 0
    },

    onLoad: function() {
        //请求分类
        this._getCategoryList();
        //请求列表信息
        this._getTopicList({
            type: "first"
        });
        //请求签到信息
        this._getSignDetail();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        if (wx.getStorageSync("pullDown")) {
            wx.startPullDownRefresh({

            })
            wx.setStorageSync("pullDown", false);
        };
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        //请求分类
        this._getCategoryList();
        //请求列表信息
        this._getTopicList({
            type: "first"
        });
        //请求签到信息
        this._getSignDetail();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        if (this.data.loadtype != "end") {
            this.setData({
                upload: true,
                loadtype: "loading"
            });
            this._getTopicList({
                type: "more"
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(options) {
        if (options.from = "button") {
            const topic = options.target.dataset.sharemodel;
            const title = topic['Content'].substring(0, 15) || "一篇精美的帖子";
            const id = topic['PostId'];
            const imgarr = topic.Images == "" ? [] : topic.Images.split(",");
            const videoarr = topic.Videos == "" ? [] : topic.Videos.split(",");
            const img = imgarr[0] || videoarr[0] || ""
            return {
                title: title,
                path: `/pages/detail/index?id=${id}`,
                imageUrl: img
            }
        }
    },
    getUserInfo: function(e) {
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    /**
     * 签到
     */
    checkin() {
        if (this.data.checkStatus) {
            this.setData({
                checklist: true
            });
        } else {
            this._toSign();
        }
    },
    /**
     * 点击帅选按钮
     */
    selecttap() {
        this.setData({
            navState: true
        });
    },
    /**
     * 点击分类按钮
     */
    navtap(e) {
        const id = e.currentTarget.dataset.id;
        let categories = this.data.categories.map(category => {
            if (category.CategoryId == id) {
                category.selected = true;
            } else {
                category.selected = false;
            }
            return category;
        });
        this.setData({
            categories: categories,
            navState: false,
            categoryId: id
        });
        setTimeout(() => {
            this._getTopicList({
                type: "first"
            });
        }, 500);

    },
    /**
     * 请求帖子的分类
     */
    _getCategoryList() {
        const that = this;
        topic.getCategoryList()
            .then(res => {
                let categoryList = res.data.Results.map(catery => {
                    catery.selected = false;
                    return catery;
                });
                categoryList.unshift({
                    CategoryId: "0",
                    IsDisplay: "1",
                    Name: "全部",
                    selected: false
                });
                that.setData({
                    categories: categoryList
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 请求帖子的列表
     */
    _getTopicList(options) {
        if (options.type == "first") {
            this.setData({
                loadtype: "loading"
            });
        }
        options.categoryId = this.data.categoryId;
        options.keyword = this.data.keyword;
        topic.getTopicList(options)
            .then(res => {
                const nowDate = new Date();
                let topicList = res.data.Results.map((topic) => {
                    //格式化帖子创建时间
                    topic.CreateTime = utils.timestampFormat(topic.CreateTime);
                    if (topic.CategoryId == 2) {
                        topic.isExpire = topic.VoteExpire < nowDate;
                        topic.VoteExpire = topic.VoteExpire.substring(0, 10);
                        topic.votes = topic.Vote.map((vote) => {
                            vote.checked = false;
                            return vote;
                        })
                    }
                    topic.Comments = topic.Comments.map((comment) => {
                        comment.CreateTime = utils.timestampFormat(comment.CreateTime);
                        comment.PostId = topic.PostId;
                        if (comment.FirstReply != '') {
                            comment.FirstReply.CreateTime = utils.timestampFormat(comment.FirstReply.CreateTime);
                        }
                        return comment;
                    });
                    return topic;
                });
                if (options.type == "first") {
                    wx.stopPullDownRefresh();
                    this.setData({
                        topicList: []
                    });
                    this.setData({
                        topicList: topicList
                    });
                } else {
                    this.setData({
                        topicList: this.data.topicList.concat(topicList),
                        upload: false
                    })
                }

                if (res.data.TotalPage <= res.data.Page) {
                    this.setData({
                        upload: true,
                        loadtype: "end"
                    });
                }
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 跳转签到日历
     */
    gotoCalender() {
        wx.navigateTo({
            url: '/pages/calender/calender',
        })
    },
    /**
     * 请求签到详情
     */
    _getSignDetail() {
        sign.signDetail()
            .then(res => {
                const signState = res.data.TodayIsSign == "Y" ? true : false
                this.setData({
                    signDetail: res.data,
                    checkStatus: signState
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                });
            });
    },
    /**
     * 点击签到
     */
    _toSign() {
        sign.sign()
            .then(res => {
                this.setData({
                    checksuccess: true,
                    ['signDetail.TodayIsSign']: "Y",
                    checkStatus: true,
                    ['signDetail.ContinuedDays']: this.data.signDetail.ContinuedDays * 1 + 1
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                });
            });
    },
    /**
     * 监听搜索输入
     */
    oninput(e) {
        this.setData({
            "keyword": e.detail.detail.value
        });
    },
    /**
     * 搜索
     */
    search() {
        this._getTopicList({
            type: "first"
        });
    },
    /**
     * 投票完成的回调
     */
    vote(e) {
        let { postId, voteId } = e.detail;
        let topics = this.data.topicList;
        let newTopics = topics.map((topic) => {
            if (topic.PostId == postId) {
                topic.LoggerCanVote = 0;
                topic.VoteNum = topic.VoteNum * 1 + voteId.length;
                topic.VoteUserNum = topic.VoteUserNum * 1 + 1;
                let votes = topic['Vote'];
                let newVotes = votes.map((vote) => {
                    let RatioAnimation = wx.createAnimation({
                        duration: 1500,
                        timingFunction: "ease-out"
                    });
                    if (voteId.indexOf(vote.VoteId) >= 0) {
                        vote.LoggerIsVote = 1;
                        vote.VoteNum = vote.VoteNum * 1 + 1;
                    }
                    if (topic.VoteNum != 0) {
                        vote.Ratio = Math.round(vote.VoteNum / topic.VoteNum * 100) + "%";
                    }

                    RatioAnimation.width(vote.Ratio).step();
                    vote['animation'] = RatioAnimation.export();
                    return vote;
                });
                topic.votes = newVotes;
            }
            return topic;
        });
        this.setData({
            topicList: newTopics
        });
    },
    /**
     * 关注回调处理数据
     */
    follow(e) {
        let { id, type } = e.detail;
        const topicList = this.data.topicList;
        let newTopicList = topicList.map((topic) => {
            if (topic.PostId == id) {
                if (type == "follow") {
                    topic.LoggerIsFollow = 1;
                    topic.FollowNum = topic.FollowNum * 1 + 1;
                } else {
                    topic.LoggerIsFollow = 0;
                    topic.FollowNum = topic.FollowNum * 1 - 1;
                }
            }
            return topic;
        });
        this.setData({
            topicList: newTopicList
        });
    },
    /**
     * 点赞回调处理数据
     */
    thumb(e) {
        let { id, type } = e.detail;
        const topicList = this.data.topicList;
        let newTopicList = topicList.map((topic) => {
            if (topic.PostId == id) {
                if (type == "like") {
                    topic.LoggerIsLike = 1;
                    topic.LikeNum = topic.LikeNum * 1 + 1;
                } else {
                    topic.LoggerIsLike = 0;
                    topic.LikeNum = topic.LikeNum * 1 - 1;
                }
            }
            return topic;
        });
        this.setData({
            topicList: newTopicList
        });
    },
    /**
     * 展示评论框
     */
    showCommentBox(e) {
        this.setData({
            subCommentState: true,
            commentPid: e.detail.pid
        });
    },
    /**
     * 隐藏评论框
     */
    hiddenComment() {
        this.setData({
            subCommentState: false
        });
    },
    /**
     * 重组评论数据
     */
    reloadComment(e) {
        const commData = e.detail;
        const pid = commData['pid'];
        const cid = commData['cid'];
        let newComment = {
            "CommentId": commData['newCommentId'],
            "FromUserId": "1",
            "Type": "2",
            "Content": commData['content'],
            "Image": commData['image'],
            "Video": commData['video'],
            "VideoCover": "",
            "CreateTime": "刚刚",
            "ReplyNum": "0",
            "LikeNum": "0",
            "FromUser": {
                "Nickname": wx.getStorageSync("nickName"),
                "Avatar": wx.getStorageSync("avatar")
            },
            "LoggerIsLike": 0,
            "FirstReply": []
        }
        if (cid == 0) {
            let newtopicList = this.data.topicList.map((topic) => {
                if (topic.PostId == pid) {
                    topic.Comments.unshift(newComment);
                    topic.CommentNum = topic.CommentNum * 1 + 1;
                }
                return topic
            });
            this.setData({
                topicList: newtopicList
            });
        }
        this.hiddenComment();
    }
})